package com.abe.mvp.view.activity;

import it.moondroid.coverflow.components.ui.containers.FeatureCoverFlow;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.abe.config.Constants;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.CoverFlowBean;
import com.abe.mvp.model.bean.MainTopBean;
import com.abe.mvp.model.bean.exercise.ExerciseGroupBean;
import com.abe.mvp.view.activity.FragmentCallbackListener.CallbackListener;
import com.abe.mvp.view.activity.base.BaseFragmentActivity;
import com.abe.mvp.view.adapter.CoverFlowAdapter;
import com.abe.mvp.view.adapter.MainTopAdapter;
import com.abe.mvp.view.fragment.ExercisePatternFragment;
import com.abe.mvp.view.fragment.ExerciseTargetFragment;
import com.abe.mvp.view.fragment.ExerciseTrailFragment;
import com.abe.mvp.view.fragment.base.BaseExerciseFragment;
import com.abe.threadmill.R;
import com.abe.utils.FileUtils;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;
import com.meetme.android.horizontallistview.HorizontalListView;

@ContentView(R.layout.activity_tm_main)
public abstract class MainViewActivity extends BaseFragmentActivity implements
		SerialPortContact.View, CallbackListener, SocketContact.View,
		OnItemClickListener, FeatureCoverFlow.OnScrollPositionListener,
		OnCompletionListener, OnClickListener {

	@ViewInject(R.id.showMessage)
	private TextView showMessage;

	/********************** 顶部信息 ************************/
	@ViewInject(R.id.main_top_list_info)
	protected HorizontalListView main_top_list_info;
	@ViewInject(R.id.main_top_layout)
	protected LinearLayout main_top_layout;
	protected List<MainTopBean> top_infos;
	protected MainTopAdapter adapter;

	/********************** 底部菜单 ************************/
	@ViewInject(R.id.main_tab_button_buffer)
	protected Button main_tab_button_buffer;
	@ViewInject(R.id.main_tab_button_start)
	protected Button main_tab_button_start;
	@ViewInject(R.id.main_tab_button_stop)
	protected Button main_tab_button_stop;
	/** 速度与坡度 */
	@ViewInject(R.id.main_tab_button_slope_plus)
	protected Button main_tab_button_slope_plus;
	@ViewInject(R.id.main_tab_button_slope_reduce)
	protected Button main_tab_button_slope_reduce;
	@ViewInject(R.id.main_tab_text_slope)
	protected TextView main_tab_text_slope;
	@ViewInject(R.id.main_tab_button_speed_plus)
	protected Button main_tab_button_speed_plus;
	@ViewInject(R.id.main_tab_button_speed_reduce)
	protected Button main_tab_button_speed_reduce;
	@ViewInject(R.id.main_tab_text_speed)
	protected TextView main_tab_text_speed;

	protected float current_slope = 0;
	/** km/h */
	protected float current_speed = 1;
	/********************** Activity与Fragment交互 ************************/
	@ViewInject(R.id.id_content)
	protected FrameLayout id_content;
	protected BaseExerciseFragment fragment;
	/** 运动模式 */
	public static final int SELECT_MOTOR_PATTERN = 0x902;
	/** 轨迹 */
	public static final int SELECT_TRAIL = 0x903;
	/** 目标 */
	public static final int SELECT_TARGET = 0x904;

	protected int currentTabFlag = SELECT_TRAIL;
	protected int currentTabPos = -1;

	protected static final int HIDE_COVERFLOW = 0x906;
	protected static final int SHOW_VIDEO = 0x907;
	protected static final int HIDE_VIDEO = 0x908;
	protected static final int SHOW_COVERFLOW = 0x909;
	protected static final int PLAY_VIDEO = 0x910;
	protected static final int STOP_VIDEO = 0x911;

	protected Boolean isFragmentRequestStop = false;
	protected ExerciseGroupBean fragmentRequestStopTempBean = null;

	/********************** 倒计时 ************************/
	@ViewInject(R.id.item_view_intercept)
	protected View item_view_intercept;
	@ViewInject(R.id.djs_text)
	protected TextView djs_text;
	protected static final int SHOW_DJS = 0x914;
	protected static final int HIDE_DJS = 0x915;
	protected static final int UPDATE_DJS_NUM = 0x916;
	protected static final int STOP_SUCCESS = 0x917;
	protected static final int SET_SPEED = 0x918;
	protected static final int SET_SLOPE = 0x919;
	protected static final int START_SUCCESS = 0x920;

	/********************** 轮播与视频 ************************/
	/** 返回、视频 */
	@ViewInject(R.id.main_left_layout_back)
	protected LinearLayout main_left_layout_back;
	@ViewInject(R.id.main_right_layout_video)
	protected LinearLayout main_right_layout_video;
	protected int videos[] = { R.raw.video1, R.raw.video2, R.raw.video3 };
	protected List<String> videoFilePaths;
	@ViewInject(R.id.item_view_coverflow)
	protected View item_view_coverflow;
	@ViewInject(R.id.item_view_videoshow)
	protected View item_view_videoshow;
	@ViewInject(R.id.video_show)
	protected VideoView video_show;
	@ViewInject(R.id.coverflow)
	protected FeatureCoverFlow mCoverFlow;
	protected CoverFlowAdapter mAdapter;
	protected ArrayList<CoverFlowBean> mData = new ArrayList<CoverFlowBean>(0);
	/** 视频类型:0:assets下；1：File替换 */
	protected int videoType = 0;
	/** -1：未选中 */
	protected int currentVideo = -1;
	/** 视频状态 */
	protected int videoStatus = Constants.VideoGone;
	/** 锻炼状态 */
	protected boolean exerciseStatus = false;
	/** 串口设置命令发送标识,0:暂无，1：设置，2：读 */
	protected int sendCommandFlag = 0;
	/** 当前是否处于正在设置启停命令 */
	protected boolean isSetStartStopCommand = false;
	/** 当前是否处于正在设置速度或者坡度 */
	protected boolean isSetQtCommand = false;
	/** 停命令重复发送次数，发送失败重发，超三次报故障 */
	protected int setStopNumber = 0;
	/**是否禁止发送（当前处于上一条命令发送150以内，防止上一组命令被冲掉）*/
	protected boolean isProhibitSend=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initTopView();
		initFragment();
		initDataAndListener();
	}

	/** 展示运动数据 */
	protected void showExerciseGroupData(ExerciseGroupBean groupBean) {
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("exercise", groupBean);
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		back();
	};

	public abstract void requestStart();

	public abstract void requestStop();

	public abstract void setSlope(float slope);

	public abstract void setSpeed(float speed);

	protected void initDataAndListener() {
		isFragmentRequestStop = false;
		fragmentRequestStopTempBean = null;
		main_tab_text_slope.setText(String.valueOf((int)current_slope)+"%");
		main_tab_text_speed.setText(String.valueOf(current_speed));
		main_tab_button_speed_reduce.setOnClickListener(this);
		main_tab_button_slope_plus.setOnClickListener(this);
		main_tab_button_slope_reduce.setOnClickListener(this);
		main_tab_button_speed_plus.setOnClickListener(this);
		main_tab_button_speed_reduce.setOnClickListener(this);
		main_left_layout_back.setOnClickListener(this);
		main_right_layout_video.setOnClickListener(this);
		main_tab_button_buffer.setOnClickListener(this);
		main_tab_button_start.setOnClickListener(this);
		main_tab_button_stop.setOnClickListener(this);
		item_view_videoshow.setOnClickListener(this);
		item_view_coverflow.setOnClickListener(this);
		djs_text.setOnClickListener(this);
	}

	protected void initCoverFlowAndVideo() {
		videoType = 0;
		/** 画廊 */
		int images[] = { R.drawable.coverflow_test_01,
				R.drawable.coverflow_test_02, R.drawable.coverflow_test_03 };
		for (int i = 0; i < images.length; i++) {
			mData.add(new CoverFlowBean(Integer.class, images[i],
					R.string.app_name));
		}
		mAdapter = new CoverFlowAdapter(this);
		mAdapter.setData(mData);
		mCoverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
		mCoverFlow.setAdapter(mAdapter);
		mCoverFlow.setOnItemClickListener(this);
		mCoverFlow.setOnScrollPositionListener(this);
		/** 视频 */
		video_show.setOnCompletionListener(this);
	}

	/**
	 * 视频加载规则
	 * 
	 * @see 加载固定文件夹下预览图片与视频文件
	 * 
	 * */
	protected void initCoverFlowAndVideoWithFile() {
		videoType = 1;
		List<File> videoImageFiles = FileUtils
				.listFilesInDir(Constants.VideoImagesBase);
		List<File> videoFiles = FileUtils.listFilesInDir(Constants.VideoBase);
		/** 取小 */
		int size = videoFiles.size() > videoImageFiles.size() ? videoImageFiles
				.size() : videoFiles.size();
		videoFilePaths = new ArrayList<>();
		if (size > 0) {
			for (int i = 0; i < size; i++) {
				mData.add(new CoverFlowBean(String.class, videoImageFiles
						.get(i).getAbsolutePath(), R.string.app_name));
				videoFilePaths.add(videoFiles.get(i).getAbsolutePath());
			}
			mAdapter = new CoverFlowAdapter(this);
			mAdapter.setData(mData);
			mCoverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
			mCoverFlow.setAdapter(mAdapter);
			mCoverFlow.setOnItemClickListener(this);
			mCoverFlow.setOnScrollPositionListener(this);
			/** 视频 */
			video_show.setOnCompletionListener(this);
		} else {
			showToast(R.string.common_video_file_error);
		}
	}

	protected void initTopView() {
		top_infos = new ArrayList<MainTopBean>();
		int[] top_names = { R.string.common_time, R.string.common_heart_rate,
				R.string.common_step_number, R.string.common_calorie,
				R.string.common_distance };
		/** 初始化顶部信息 */
		for (int i = 0; i < 5; i++) {
			MainTopBean info = new MainTopBean();
			info.setName(NormalUtils.getString(top_names[i]));
			info.setData("0");
			top_infos.add(info);
		}
		adapter = new MainTopAdapter(getApplicationContext(), top_infos, scale);
		main_top_list_info.setAdapter(adapter);
	}

	/** 添加子页面 */
	protected void initFragment() {
		Bundle bundle = getIntent().getExtras();
		currentTabFlag = bundle.getInt("tab", SELECT_TRAIL);
		currentTabPos = bundle.getInt("pos", -1);
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.commit();
		switch (currentTabFlag) {
		case SELECT_MOTOR_PATTERN:
			fragment = new ExercisePatternFragment();
			break;
		case SELECT_TRAIL:
			fragment = new ExerciseTrailFragment();
			break;
		case SELECT_TARGET:
			fragment = new ExerciseTargetFragment();
			break;
		}
		transaction.replace(R.id.id_content, fragment);
		current_slope = 0;
		current_speed = 1;
	}

	/** 画廊滑动结束 */
	@Override
	public void onScrolledToPosition(int position) {

	}

	/** 画廊滑动中 */
	@Override
	public void onScrolling() {

	}

	/** 循环播放设置 */
	@Override
	public void onCompletion(MediaPlayer mp) {
		localSendEmptyMessage(PLAY_VIDEO);
	}

	/** 画廊点击播放 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (parent.equals(mCoverFlow)) {
			/** 隐藏画廊 */
			localSendEmptyMessage(HIDE_COVERFLOW);
			/** 当前选中播放视频 */
			currentVideo = mCoverFlow.getFirstVisiblePosition();
			localSendEmptyMessage(PLAY_VIDEO);
			videoStatus = Constants.VideoPlayVisible;
		}
	}

	/** 设置停止命令状态监测，超时重发，3次报故障 */
	protected class CheckStopStatus implements Runnable {

		@Override
		public void run() {
			try {
				while (setStopNumber <= 3 && exerciseStatus) {
					/** 停止失败,重发 */
					setStopNumber++;
					requestStop();
					/** 停止命令发送后等待150ms */
					Thread.sleep(150);
				}
				if (exerciseStatus) {
					/** 三次停止失败,报故障 */
					showToast(R.string.send_message_error);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	/** 延时150ms发送命令 */
	class DelaySendSpeedSlope implements Runnable {
		@Override
		public void run() {
			isProhibitSend=true;
			try {
				Thread.sleep(150);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			isProhibitSend=false;
		}
	}

	/** Handler快捷 */
	protected void localSendMessage(int what, Object object) {
		new MyHandler(Looper.getMainLooper()).sendMessage(NormalUtils
				.getMessage(what, object));
	}

	/** Handler快捷 */
	protected void localSendEmptyMessage(int What) {
		new MyHandler(Looper.getMainLooper()).sendEmptyMessage(What);
	}

	class MyHandler extends Handler {
		public MyHandler(Looper looper) {
			super(looper);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0x999: {
				showMessage.setText(msg.obj.toString());
			}
				break;
			case SET_SPEED: {
				main_tab_text_speed.setText(String.valueOf(current_speed));
				fragment.setSpeed(current_speed);
			}
				break;
			case SET_SLOPE: {
				main_tab_text_slope.setText(String.valueOf((int)current_slope)+"%");
				fragment.setSlope(current_slope);
			}
				break;
			case START_SUCCESS: {
				/** 启动 */
				fragment.startExercise();
			}
				break;
			case STOP_SUCCESS: {
				/** 处于运动状态 */
				/** 当前视频正在播放 */
				if (videoStatus == Constants.VideoPlayGone
						|| videoStatus == Constants.VideoPlayVisible) {
					videoStatus = Constants.VideoGone;
					/** 隐藏视频播放 */
					localSendEmptyMessage(HIDE_VIDEO);
					/** 停止播放视频 */
					localSendEmptyMessage(STOP_VIDEO);
				}
				/** 停止 */
				if (isFragmentRequestStop) {
					showExerciseGroupData(fragmentRequestStopTempBean);
				} else {
					fragment.stopExercise();
				}
			}
				break;
			case UPDATE_DJS_NUM: {
				djs_text.setText(msg.obj.toString());
			}
				break;
			case SHOW_DJS: {
				if (fragment.checkInitComplete()) {
					item_view_intercept.setVisibility(View.VISIBLE);
					new CountDownTimer(31 * 100, 100) {
						int i = 30;

						@Override
						public void onTick(long millisUntilFinished) {
							if (i % 10 == 0) {
								/** 每隔countDownInterval秒会回调一次onTick()方法 */
								localSendMessage(UPDATE_DJS_NUM, i / 10);
							}
							i--;
						}

						@Override
						public void onFinish() {
							localSendEmptyMessage(HIDE_DJS);
						}
					}.start();
				}
			}
				break;
			case HIDE_DJS: {
				item_view_intercept.setVisibility(View.GONE);
				localSendMessage(UPDATE_DJS_NUM, "");
				requestStart();
			}
				break;

			/********************************/
			case PLAY_VIDEO:
				Uri uri = null;
				if (videoType == 0) {
					uri = Uri.parse("android.resource://" + getPackageName()
							+ "/" + videos[currentVideo]);
				} else if (videoType == 1) {
					uri = Uri.parse(videoFilePaths.get(currentVideo));
				}
				if (uri != null) {
					video_show.setVideoURI(uri);
					video_show.start();
					if (videoStatus == Constants.VideoPlayVisible) {
						/** 显示视频 */
						localSendEmptyMessage(SHOW_VIDEO);
					}
				}
				break;
			case STOP_VIDEO:
				if (video_show.isPlaying()) {
					video_show.stopPlayback();
				}
				break;
			case SHOW_COVERFLOW:
				item_view_coverflow.setVisibility(View.VISIBLE);
				main_top_layout.setVisibility(View.GONE);
				break;
			case SHOW_VIDEO:
				item_view_videoshow.setVisibility(View.VISIBLE);
				main_top_layout.setVisibility(View.VISIBLE);
				break;
			case HIDE_COVERFLOW:
				item_view_coverflow.setVisibility(View.GONE);
				main_top_layout.setVisibility(View.VISIBLE);
			case HIDE_VIDEO:
				item_view_videoshow.setVisibility(View.GONE);
				main_top_layout.setVisibility(View.VISIBLE);
				break;
			/********************************/
			case Constants.MainTopTime: {
				/** 更新时间信息 */
				MainTopBean bean = top_infos.get(0);
				bean.setData(msg.obj.toString());
				top_infos.set(0, bean);
				adapter.notifyDataSetChanged();
			}
				break;
			case Constants.MainTopHeartRate: {
				/** 更新心率信息 */
				MainTopBean bean = top_infos.get(1);
				bean.setData(msg.obj.toString());
				top_infos.set(1, bean);
				adapter.notifyDataSetChanged();
			}
				break;
			case Constants.MainTopSteps: {
				/** 更新步数信息 */
				MainTopBean bean = top_infos.get(2);
				bean.setData(msg.obj.toString());
				top_infos.set(2, bean);
				adapter.notifyDataSetChanged();
			}
				break;
			case Constants.MainTopCalorie: {
				/** 更新卡路里信息 */
				MainTopBean bean = top_infos.get(3);
				bean.setData(msg.obj.toString());
				top_infos.set(3, bean);
				adapter.notifyDataSetChanged();
			}
				break;
			case Constants.MainTopDistance: {
				/** 更新距离信息 */
				MainTopBean bean = top_infos.get(4);
				bean.setData(msg.obj.toString());
				top_infos.set(4, bean);
				adapter.notifyDataSetChanged();
			}
				break;

			default:
				break;
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_tab_button_slope_plus: {
			if (current_slope + 1 <= Constants.SlopeMax && exerciseStatus) {
				setSlope(current_slope + 1);
			}
		}
			break;
		case R.id.main_tab_button_slope_reduce: {
			if (current_slope - 1 >= Constants.SlopeStart && exerciseStatus) {
				setSlope(current_slope - 1);
			}
		}
			break;
		case R.id.main_tab_button_speed_plus: {
			if (current_speed + 0.5f <= Constants.SpeedMax && exerciseStatus) {
				if (fragment.checkIsCanSetSpeedSlope()&&!isProhibitSend) {
					setSpeed(current_speed + 0.5f);
				}
			}
		}
			break;
		case R.id.main_tab_button_speed_reduce: {
			if (current_speed - 0.5f >= Constants.SpeedStart && exerciseStatus) {
				if (fragment.checkIsCanSetSpeedSlope()&&!isProhibitSend) {
					setSpeed(current_speed - 0.5f);
				}
			}
		}
			break;
		case R.id.main_left_layout_back: {
			if (!exerciseStatus) {
				back();
			} else {
				showToast(R.string.common_please_stop_exercise);
			}
		}
			break;
		case R.id.main_right_layout_video: {
			chooseVideo();
		}
			break;
		case R.id.main_tab_button_buffer: {
		}
			break;
		case R.id.main_tab_button_start: {
			if (!exerciseStatus) {
				/** 在关闭状态下设置启动成功 */
				localSendEmptyMessage(SHOW_DJS);
			}
		}
			break;
		case R.id.main_tab_button_stop: {
			ThreadPoolUtils.execute(new CheckStopStatus());
		}
			break;
		case R.id.item_view_videoshow: {
			videoStatus = Constants.VideoPlayGone;
			/** 隐藏视频播放 */
			localSendEmptyMessage(HIDE_VIDEO);
		}
			break;
		case R.id.item_view_coverflow: {
			videoStatus = Constants.VideoGone;
			/** 隐藏画廊 */
			localSendEmptyMessage(HIDE_COVERFLOW);
		}
			break;
		case R.id.djs_text: {
		}
			break;
		}
	}

}
